/*
 ============================================================================
 Name        : linuxdaemon.c
 Author      : Krzysztof Kardasz
 Version     :
 Copyright   : Krzysztof Kardasz
 Description : Hello World in C, Ansi-style
 ============================================================================
 http://www.netzmafia.de/skripten/unix/linux-daemon-howto.html
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> // fork

#include <sys/stat.h> // umask
/*
 #include <signal.h>
 #include <syslog.h>
 #include <string.h>


 #include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <syslog.h>
#include <string.h>
 */

int main(void)
{
    pid_t pid, sid;

    pid = fork();
    if (pid < 0) {
        return EXIT_FAILURE;
    }
    if (pid > 0) {
        return EXIT_SUCCESS;
    }

    umask(0);

    const char pidflie[] = "/var/run/mydaemon2.pid";
    FILE * pidfp = fopen(pidflie, "w");
    if (pidfp == NULL) {
        fprintf(stderr, "Can't write to file %s\n", pidflie);
        return EXIT_FAILURE;
    }
    fprintf(pidfp, "%d", getpid());
    fclose(pidfp);

    sid = setsid();
    if (sid < 0) {
        exit(EXIT_FAILURE);
    }

    const char root[] = "/tmp";
    if (chroot(root) < 0) {
        fprintf(stderr, "Cannot change the root directory %s\n", root);
        exit(EXIT_FAILURE);
    }

    if ((chdir("/")) < 0) {
        fprintf(stderr, "Change the current working directory '/'\n");
        exit(EXIT_FAILURE);
    }

    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);

    if (fork() == 0) {
        // Dziecko
        while (1) {
            sleep(30);
        }
    } else {
        // Rodzic
        while (1) {
            sleep(30);
        }
    }

    return EXIT_SUCCESS;
}
